package com.haohan.cloud.scm.common.tools.thread;

import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author dy
 * @date 2020/3/12
 * 全局使用 线程池
 */
public class ScmGlobalThreadPool {

    private ScmGlobalThreadPool() {
    }

    private static class PoolHolder {
        private static final ThreadPoolTaskExecutor TASK_EXECUTOR = new ThreadPoolTaskExecutor();

        static {
            // 设置线程池核心容量
            TASK_EXECUTOR.setCorePoolSize(5);
            // 设置线程池最大容量
            TASK_EXECUTOR.setMaxPoolSize(10);
            // 设置任务队列长度
            TASK_EXECUTOR.setQueueCapacity(1000000);
            // 设置线程超时时间
            TASK_EXECUTOR.setKeepAliveSeconds(60);
            // 设置线程名称前缀
            TASK_EXECUTOR.setThreadFactory(new NamedThreadFactory("scm-thread-"));
            // 设置任务丢弃后的处理策略
            TASK_EXECUTOR.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
            // 设置任务的装饰
            TASK_EXECUTOR.setTaskDecorator(new ContextCopyingDecorator());
            TASK_EXECUTOR.initialize();
        }
    }

    public static AsyncTaskExecutor getExecutor() {
        return PoolHolder.TASK_EXECUTOR;
    }

}
